/*
 *  beluga_chat.c
 *  purple-beluga
 *
 */

#include "beluga_chat.h"

//send message to chat
//poll for messages
//fetch chat history

/*
int  (*chat_send)(PurpleConnection *, int id, const char *message, PurpleMessageFlags flags);
 */


gint64 beluga_time_kludge(gint initial_time)
{
	if (sizeof(gint) >= sizeof(gint64))
		return initial_time;
	
	gint64 now_millis = (gint64) time(NULL);
	now_millis *= 1000;
	now_millis &= 0xFFFFFFFF00000000LL;
	gint64 final_time = now_millis | ((guint)initial_time);

	return final_time;
}


void
beluga_chat_messages_cb(BelugaAccount *na, const gchar *request, gchar *response, gsize len, gpointer userdata)
{
	/* BelugaChat *chat; */
	/* JsonObject *obj; */
	/* JsonArray *array; */
	/* JsonObject *msgobj; */
	/* const gchar *type; */
	/* const gchar *body; */
	/* const gchar *roomId; */
	/* const gchar *targetId; */
	/* gint date; */
	/* JsonObject *sender; */
	/* const gchar *senderId; */
	/* PurpleBuddy *buddy; */
	/* PurpleGroup *group; */
	/* guint i; */
	/* guint64 time_kludge; */
	
	/* chat = userdata; */
	
	/* purple_debug_info("beluga", "beluga_chat_messages_cb: %s\n", response?response:"(null)"); */
	/* obj = beluga_json_parse(response, len); */
	
	/* if (json_object_has_member(obj, "hash")) */
	/* { */
	/* 	g_free(chat->beluga_hash); */
	/* 	chat->beluga_hash = g_strdup(json_node_get_string(json_object_get_member(obj, "hash"))); */
	/* } */
	
	/* array = json_node_get_array(json_object_get_member(obj, "messages")); */
	/* for(i = 0; i < json_array_get_length(array); i++) */
	/* { */
	/* 	msgobj = json_node_get_object(json_array_get_element(array, i)); */
	/* 	//type (message or private) */
	/* 	//body, date, roomId, targetId, sender(obj) */
	/* 	type = json_node_get_string(json_object_get_member(msgobj, "type")); */
	/* 	body = json_node_get_string(json_object_get_member(msgobj, "body")); */
	/* 	date = json_node_get_int(json_object_get_member(msgobj, "date")); */
	/* 	roomId = json_node_get_string(json_object_get_member(msgobj, "roomId")); */
	/* 	targetId = json_node_get_string(json_object_get_member(msgobj, "targetId")); */
	/* 	sender = json_node_get_object(json_object_get_member(msgobj, "sender")); */
	/* 	senderId = json_node_get_string(json_object_get_member(sender, "belugaId")); */
		
	/* 	//Check that they're on the buddy list */
	/* 	buddy = purple_find_buddy(na->account, senderId); */
	/* 	if (!buddy) */
	/* 	{ */
	/* 		//They aren't, so lets fake it */
	/* 		buddy = purple_buddy_new(na->account, senderId,  */
	/* 								 json_node_get_string(json_object_get_member(sender, "name"))); */
	/* 		group = purple_find_group(BELUGA_TEMP_GROUP_NAME); */
	/* 		if (!group) */
	/* 		{ */
	/* 			group = purple_group_new(BELUGA_TEMP_GROUP_NAME); */
	/* 			purple_blist_add_group(group, NULL); */
	/* 			purple_blist_node_set_flags(&group->node, PURPLE_BLIST_NODE_FLAG_NO_SAVE); */
	/* 		} */
	/* 		purple_blist_add_buddy(buddy, NULL, group, NULL); */
	/* 		purple_blist_node_set_flags(&buddy->node, PURPLE_BLIST_NODE_FLAG_NO_SAVE); */
	/* 	} */
		
	/* 	time_kludge = beluga_time_kludge(date); */
		
	/* 	if (g_str_equal(type, "message")) */
	/* 	{ */
	/* 		serv_got_chat_in(na->pc, chat->purple_id, senderId, PURPLE_MESSAGE_RECV, body, time_kludge); */
	/* 	} else if (g_str_equal(type, "private")) */
	/* 	{ */
	/* 		serv_got_chat_in(na->pc, chat->purple_id, senderId, */
	/* 						 PURPLE_MESSAGE_RECV | PURPLE_MESSAGE_WHISPER, body, time_kludge); */
	/* 	} else { */
	/* 		purple_debug_info("beluga", "unknown message type: %s\n", type); */
	/* 	} */
	/* } */
	
	/* json_object_unref(obj); */
}

gboolean
beluga_chat_get_history(BelugaChat *chat)
{
	BelugaAccount *na;
	gchar *url;
	gchar *encoded_hash;
	gchar *encoded_app;
	gchar *encoded_id;
	gchar *encoded_token;
	gchar *encoded_room;
	
	na = chat->na;
	
	encoded_hash = g_strdup(purple_url_encode(chat->beluga_hash));
	encoded_app = g_strdup(purple_url_encode(na->beluga_app));
	encoded_id = g_strdup(purple_url_encode(na->beluga_id));
	encoded_token = g_strdup(purple_url_encode(na->chat_token));
	encoded_room = g_strdup(purple_url_encode(chat->roomId));
	
	url = g_strdup_printf("/xn/groupchat/list?h=%s&a=%s&i=%s&t=%s&r=%s", encoded_hash, encoded_app,
						  encoded_id, encoded_token, encoded_room);
	
	beluga_post_or_get(na, BELUGA_METHOD_GET, na->chat_domain,
					 url, NULL, 
					 beluga_chat_messages_cb, chat, FALSE);
	
	g_free(url);
	g_free(encoded_room);
	g_free(encoded_token);
	g_free(encoded_id);
	g_free(encoded_app);
	g_free(encoded_hash);
	
	return FALSE;
}

void
beluga_chat_get_users_cb(BelugaAccount *na, const gchar *request, gchar *response, gsize len, gpointer userdata)
{
/* 	BelugaChat *chat; */
/* 	JsonObject *obj; */
/* 	JsonArray *array; */
/* 	JsonObject *userobj; */
/* 	int i; */
/* 	const gchar *belugaId; */
/* 	const gchar *name; */
/* 	//const gchar *iconUrl; */
/* 	gboolean isAdmin; */
/* 	PurpleConversation *conv; */
/* //	PurpleBuddy *buddy; */
/* 	PurpleConvChatBuddy *cbuddy; */
/* 	PurpleConversationUiOps *uiops; */

/* 	purple_debug_info("beluga", "chat users: %s\n", response?response:"(null)"); */
	
/* 	chat = userdata; */
/* 	obj = beluga_json_parse(response, len); */
	
/* 	if (json_object_has_member(obj, "hash")) */
/* 	{ */
/* 		g_free(chat->beluga_hash); */
/* 		chat->beluga_hash = g_strdup(json_node_get_string(json_object_get_member(obj, "hash"))); */
/* 	} */
	
/* 	conv = purple_find_chat(na->pc, chat->purple_id); */
/* 	uiops = purple_conversation_get_ui_ops(conv); */

/* 	array = json_node_get_array(json_object_get_member(obj, "expired")); */
/* 	for(i = 0; i < json_array_get_length(array); i++) */
/* 	{ */
/* 		belugaId = json_node_get_string(json_array_get_element(array, i)); */
/* 		purple_conv_chat_remove_user(PURPLE_CONV_CHAT(conv), belugaId, NULL); */
/* 	} */
	
/* 	array = json_node_get_array(json_object_get_member(obj, "users")); */
/* 	if (array && json_array_get_length(array) > 0) */
/* 	{ */
/* 		purple_conv_chat_clear_users(PURPLE_CONV_CHAT(conv)); */
/* 	} */
/* 	for(i = 0; i < json_array_get_length(array); i++) */
/* 	{ */
/* 		userobj = json_node_get_object(json_array_get_element(array, i)); */
/* 		//isNC, iconUrl, name, belugaId, isAdmin */
/* 		belugaId = json_node_get_string(json_object_get_member(userobj, "belugaId")); */
/* 		name = json_node_get_string(json_object_get_member(userobj, "name")); */
/* 		isAdmin = json_node_get_boolean(json_object_get_member(userobj, "isAdmin")); */
		
/* 		if (!purple_conv_chat_find_user(PURPLE_CONV_CHAT(conv), belugaId)) */
/* 		{ */
/* 			purple_conv_chat_add_user(PURPLE_CONV_CHAT(conv), belugaId,  */
/* 				NULL, isAdmin?PURPLE_CBFLAGS_OP:PURPLE_CBFLAGS_NONE, */
/* 				FALSE); */
/* 		} */
/* 		cbuddy = purple_conv_chat_cb_find(PURPLE_CONV_CHAT(conv), belugaId); */
/* 		if (cbuddy) */
/* 		{ */
/* 			g_free(cbuddy->alias); */
/* 			cbuddy->alias = g_strdup(name); */
/* 		} */
/* 		//Refresh the buddy */
/* 		if (uiops && uiops->chat_rename_user) */
/* 		{ */
/* 			purple_debug_info("beluga", "try rename user %s to %s\n", belugaId, name); */
/* 			uiops->chat_rename_user(conv, belugaId, belugaId, name); */
/* 		} */
/* 		else if (uiops && uiops->chat_update_user) */
/* 		{ */
/* 			purple_debug_info("beluga", "try update user %s\n", belugaId); */
/* 			uiops->chat_update_user(conv, belugaId); */
/* 		} */
/* 	} */
		
/* 	json_object_unref(obj); */
}

gboolean
beluga_chat_get_users(BelugaChat *chat)
{
	BelugaAccount *na;
	gchar *url;
	gchar *encoded_hash;
	gchar *encoded_app;
	gchar *encoded_id;
	gchar *encoded_token;
	gchar *encoded_room;
	
	na = chat->na;
	
	encoded_hash = g_strdup(purple_url_encode(chat->beluga_hash));
	encoded_app = g_strdup(purple_url_encode(na->beluga_app));
	encoded_id = g_strdup(purple_url_encode(na->beluga_id));
	encoded_token = g_strdup(purple_url_encode(na->chat_token));
	encoded_room = g_strdup(purple_url_encode(chat->roomId));
	
	url = g_strdup_printf("/xn/presence/list?h=%s&a=%s&i=%s&t=%s&r=%s", encoded_hash, encoded_app,
							   encoded_id, encoded_token, encoded_room);
	
	beluga_post_or_get(na, BELUGA_METHOD_GET, na->chat_domain,
					 url, NULL, 
					 beluga_chat_get_users_cb, chat, FALSE);
	
	g_free(url);
	g_free(encoded_room);
	g_free(encoded_token);
	g_free(encoded_id);
	g_free(encoded_app);
	g_free(encoded_hash);
	
	return TRUE;
}

gboolean
beluga_chat_poll_messages(BelugaChat *chat)
{
	BelugaAccount *na;
	gchar *url;
	gchar *encoded_app;
	gchar *encoded_id;
	gchar *encoded_token;
	gchar *encoded_room;
	
	na = chat->na;
	
	encoded_app = g_strdup(purple_url_encode(na->beluga_app));
	encoded_id = g_strdup(purple_url_encode(na->beluga_id));
	encoded_token = g_strdup(purple_url_encode(na->chat_token));
	encoded_room = g_strdup(purple_url_encode(chat->roomId));
	
	url = g_strdup_printf("/xn/groupchat/poll?a=%s&i=%s&t=%s&r=%s", encoded_app,
						  encoded_id, encoded_token, encoded_room);
	
	beluga_post_or_get(na, BELUGA_METHOD_GET, na->chat_domain,
					 url, NULL, 
					 beluga_chat_messages_cb, chat, FALSE);
	
	g_free(url);
	g_free(encoded_room);
	g_free(encoded_token);
	g_free(encoded_id);
	g_free(encoded_app);
	
	return TRUE;
}

void
beluga_chat_cb(BelugaAccount *na, const gchar *request, gchar *response, gsize len, gpointer userdata)
{
	PurpleConversation *conv;
	
	conv = userdata;
	
	purple_debug_info("beluga", "beluga_chat_cb: %s\n", response?response:"(null)");
}

void
beluga_chat_whisper(PurpleConnection *pc, int id, const char *who, const char *message)
{
	/* BelugaAccount *na; */
	/* gchar *stripped; */
	/* PurpleConversation *conv; */
	/* gchar *postdata; */
	/* gchar *message_json; */
	/* gchar *sender; */
	
	/* gchar *message_escaped; */
	/* gchar *beluga_id_escaped; */
	/* gchar *token_escaped; */
	/* gchar *room_escaped; */
	/* gchar *app_escaped; */
	
	/* purple_debug_info("beluga", "chat whisper %s %s\n", who, message); */
	
	/* na = pc->proto_data; */
	/* conv = purple_find_chat(pc, id); */
	
	/* app_escaped = g_strdup(purple_url_encode(na->beluga_app)); */
	/* token_escaped = g_strdup(purple_url_encode(na->xg_token)); */
	/* room_escaped = g_strdup(purple_url_encode(conv->name)); */
	/* beluga_id_escaped = g_strdup(purple_url_encode(na->beluga_id)); */
	
	/* sender = build_user_json(na); */
	
	/* stripped = purple_markup_strip_html(message); */
	/* if (who != NULL) */
	/* { */
	/* 	message_json = g_strdup_printf("{ \"roomId\":\"%s\", \"type\":\"private\", \"targetId\":\"%s\", \"body\":\"%s\", \"sender\":%s }", */
	/* 								  conv->name, who, stripped, */
	/* 								  sender); */
	/* } else { */
	/* 	message_json = g_strdup_printf("{ \"roomId\":\"%s\", \"type\":\"message\", \"targetId\":null, \"body\":\"%s\", \"sender\":%s }", */
	/* 								  conv->name, stripped, */
	/* 								  sender);		 */
	/* } */
	/* message_escaped = g_strdup(purple_url_encode(message_json)); */
	
	/* postdata = g_strdup_printf("a=%s&i=%s&t=%s&r=%s&message=%s", */
	/* 						   app_escaped, beluga_id_escaped, */
	/* 						   token_escaped, room_escaped, */
	/* 						   message_escaped); */
	
	/* beluga_post_or_get(na, BELUGA_METHOD_POST, na->chat_domain, */
	/* 				 "/xn/groupchat/publish", postdata,  */
	/* 				 beluga_chat_cb, conv, FALSE); */
	
	/* g_free(sender); */
	/* g_free(postdata); */
	/* g_free(message_escaped); */
	/* g_free(message_json); */
	/* g_free(stripped); */
	/* g_free(app_escaped); */
	/* g_free(beluga_id_escaped); */
	/* g_free(token_escaped); */
	/* g_free(room_escaped); */
}

int
beluga_chat_send(PurpleConnection *pc, int id, const char *message, PurpleMessageFlags flags)
{
	if (flags != PURPLE_MESSAGE_SEND)
		return -1;
	
	beluga_chat_whisper(pc, id, NULL, message);
	return 1;
}

